<template>
  <div id="table_container">
    <el-card style="margin-bottom: 5px; text-align: left;">
      <el-input v-model="keyWord" placeholder="输入搜索内容" style="width: 200px;" @keyup.enter.native="handleFilter"></el-input>
      <el-select v-model="status" placeholder="状态" style="width: 90px;margin-left: 10px;">
        <el-option v-for="item in importanceOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 10px;">
        查询
      </el-button>
      <el-button v-permission="['patient:add']" class="create_btn" style="float: right;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </el-card>
    <el-card>
      <el-table
          :data="tableData"
          v-loading="loading"
          row-key="id"
          border>
        <el-table-column
            type="index"
            label="序号"
            align="center"
            width="50">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名">
        </el-table-column>
        <el-table-column
            prop="gender_label"
            width="50"
            label="性别">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号码">
        </el-table-column>
        <el-table-column
            prop="id_card"
            label="身份证号"
            width="170">
        </el-table-column>
        <el-table-column
            prop="parent_name"
            label="父母姓名">
        </el-table-column>
        <el-table-column
            prop="parent_phone"
            label="父母手机">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="70">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.status === true ? 'success' :'danger' "
                disable-transitions>{{ scope.row.status === true ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            width="300"
            align="center"
            label="操作">
          <template slot-scope="scope">
            <el-button @click="handleLookupAll(scope.row)" type="success" icon="el-icon-view" size="small">所有报告</el-button>
            <el-button v-permission="['patient:edit']" @click="handleEdit(scope.row)" type="primary" icon="el-icon-edit" size="small">编辑</el-button>
            <el-button v-permission="['patient:delete']" @click="handleDelete(scope.row)" type="danger" icon="el-icon-delete" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="pageTotal>0"
          :total="pageTotal"
          :page.sync="page"
          :pageSize.sync="pageSize"
          @pagination="getDataList"/>
    </el-card>

    <el-dialog title="新建" width="400px" @close="handleClose" :visible.sync="createDialogFormVisible">
      <el-form :model="formData" style="text-align: left" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="formData.id_card"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model.number="formData.phone"></el-input>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
              style="width: 100%"
              v-model="formData.birth"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="父母姓名">
          <el-input v-model="formData.parent_name"></el-input>
        </el-form-item>
        <el-form-item label="父母电话">
          <el-input v-model.number="formData.parent_phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCreatePatient">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看" width="400px" @close="handleClose" :visible.sync="showDialogFormVisible">
      <el-form disabled :model="formData" style="text-align: left" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="formData.id_card"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model.number="formData.phone"></el-input>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
              style="width: 100%"
              v-model="formData.birth"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="父母姓名">
          <el-input v-model="formData.parent_name"></el-input>
        </el-form-item>
        <el-form-item label="父母电话">
          <el-input v-model.number="formData.parent_phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="showDialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑" width="400px" @close="handleClose" :visible.sync="editDialogFormVisible">
      <el-form :model="formData" style="text-align: left" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="formData.id_card"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model.number="formData.phone"></el-input>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
              style="width: 100%"
              v-model="formData.birth"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="父母姓名">
          <el-input v-model="formData.parent_name"></el-input>
        </el-form-item>
        <el-form-item label="父母电话">
          <el-input v-model.number="formData.parent_phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdatePatient">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {createPatient, createReport, deletePatient, getPatient, updatePatient} from "@/api";
import pagination from "@/components/Pagenation";

export default {
  name: "index",
  components: {
    pagination
  },
  data() {
    return {
      tableData: [],
      loading: true,
      keyWord: undefined,
      importanceOptions: [{label: '启用', value: 1}, {label: '停用', value: 0}],
      status: undefined,
      // 分页器相关
      page: 1,
      pageTotal: 0,
      pageSize: 10,

      createDialogFormVisible: false,
      showDialogFormVisible: false,
      editDialogFormVisible: false,
      formData: {
        name: undefined,
        id_card: undefined,
        gender: 0,
        birth: undefined,
        phone: undefined,
        parent_name: undefined,
        parent_phone: undefined,
        status: true
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: '姓名不能为空', trigger: 'blur'}
        ],
        id_card: [
          {required: true, message: '身份证号不能为空', trigger: 'blur'},
          {validator: this.validID, trigger: 'blur'}
        ]
      },
      stageOptions: [
        {label: "幼儿园", value: "幼儿园"},
        {label: "小学", value: "小学"},
        {label: "初中", value: "初中"},
        {label: "高中", value: "高中"},
        {label: "其他", value: "其他"},
      ]

    }
  },
  mounted() {
    this.getDataList()
  },
  methods: {
    getDataList(params = {}) {
      this.loading = true

      params['page'] = this.page
      params['pageSize'] = this.pageSize
      params['keyWord'] = this.keyWord
      params['status'] = this.status
      getPatient(params).then(res => {
        this.tableData = res.data.results;
        this.pageTotal = res.data.count;
        setTimeout(() => {
          this.loading = false
        }, 1.5 * 500)
      })
    },
    handleFilter() {
      this.getDataList()
    },
    handleClose() {
      this.formData = {
        name: undefined,
        id_card: undefined,
        gender: 0,
        birth: undefined,
        phone: undefined,
        parent_name: undefined,
        parent_phone: undefined,
        status: true
      }
    },
    handleCreate() {
      this.createDialogFormVisible = true

    },
    async createReport() {
      let stageOptions = ['幼儿园', '小学', '初中', '高中', '其他']
      this.createDialogFormVisible = true
      let data = this.handleClick()
      console.log(data)
      for (let i = 0; i < data.length; i++) {
        data[i].stage = stageOptions[Math.round(Math.random() * 4)]
        await this.temp(data[i])
      }
    },
    temp(item) {
      return new Promise((resolve, reject) => {
        createReport(item).then(res => {
          this.$message.success('新建成功！')
          // this.createDialogFormVisible = false
          // this.$router.go(0)
          // this.getDataList()
          setTimeout(() => {
            resolve()
          }, 300)
        })
      })

    },
    submitCreatePatient() {
      let data = this.formData
      createPatient(data).then(res => {
        this.$message.success('新建成功！')
        this.createDialogFormVisible = false
        // this.$router.go(0)
        this.getDataList()
      })
    },
    submitUpdatePatient() {
      let data = this.formData
      updatePatient(data).then(res => {
        this.$message.success('修改成功！')
        this.editDialogFormVisible = false
        this.getDataList()
      })
    },
    // 身份证验证
    async validID(rule, value, callback) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(value)) {
        await this.go(value.length);
        callback()
      } else {
        callback(new Error('身份证号码不正确'))
      }
    },
    // 实现自动生成生日，性别，年龄
    go(val) {
      let iden = this.formData.id_card;
      let sex = null;
      let birth = null;
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = 0;

      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        sex = iden.substring(16, 17);
        birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
        if (iden.substring(10, 12) < month || iden.substring(10, 12) === month && iden.substring(12, 14) <= day) age++;

      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
        sex = iden.substring(13, 14);
        birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
        if (iden.substring(8, 10) < month || iden.substring(8, 10) === month && iden.substring(10, 12) <= day) age++;
      }

      if (sex % 2 === 0)
        sex = 2;
      else
        sex = 1;
      //性别  ==> 1:男       2:女
      this.formData.age = age;
      this.formData.gender = sex;
      this.formData.birth = birth;
    },
    handleShow(row) {
      this.formData = {...row}
      this.showDialogFormVisible = true
    },
    handleEdit(row) {
      this.formData = {...row}
      this.editDialogFormVisible = true
    },
    handleDelete(row) {
      deletePatient(row.id).then(res => {
        this.$message.success('删除成功')
        this.getDataList()
      })
    },
    handleLookupAll(row) {
      this.$router.push({name: 'report', params: {patientId: row.id}})
    },

    handleClick(row) {
      // 使用 Mock
      var Mock = require('mockjs')
      Mock.Random.extend({
        phone: function () {
          var phonePrefixs = ['132', '135', '189'] // 自己写前缀哈
          return this.pick(phonePrefixs) + Mock.mock(/\d{8}/) //Number()
        }
      })
      var data = Mock.mock({
        // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
        'data|3000': [{
          // 属性 id 是一个自增数，起始值为 1，每次增 1
          "patient": "@integer(1,5056)",
          "OS_VASC": "@float(4,5,1,1)",
          "OD_VASC": "@float(4,5,1,1)",
          "OS_Sph": "@float(-4,4,2,2)",
          "OD_Sph": "@float(-4,4,2,2)",
          "OS_Cyl": "@float(-4,4,2,2)",
          "OD_Cyl": "@float(-4,4,2,2)",
          "OS_Axis": "@integer(1,180)",
          "OD_Axis": "@integer(1,180)",
          "OS_SE": "@float(-4,4,2,2)",
          "OD_SE": "@float(-4,4,2,2)",
          "batch": "@integer(1,12)",
          "doctor": "@integer(1,18)",

        }]
      })
      return data.data
    },

  }

}
</script>

<style scoped>

</style>